package freespiritsocial.io.user.chat

import com.sendbird.android.SendBird
import com.sendbird.android.SendBird.ConnectHandler
import com.sendbird.android.SendBird.DisconnectHandler
import freespiritsocial.io.user.util.CacheUtil

object ConnectionManager {
    fun isLogin(): Boolean {
        return CacheUtil.isLogin()
    }

    fun login(userId: String?,handler: ConnectHandler?) {
        SendBird.connect(userId) { user,e -> handler?.onConnected(user,e) }
    }

    fun logout(handler: DisconnectHandler?) {
        SendBird.disconnect { handler?.onDisconnected() }
    }

    fun addConnectionManagementHandler(handlerId: String?,handler: (Boolean) -> Unit) {
        SendBird.addConnectionHandler(handlerId,object: SendBird.ConnectionHandler {
            override fun onReconnectStarted() {}
            override fun onReconnectSucceeded() {
                handler(true)
            }

            override fun onReconnectFailed() {}
        })
        if (SendBird.getConnectionState() == SendBird.ConnectionState.OPEN) {
            handler(false)
        } else if (SendBird.getConnectionState() == SendBird.ConnectionState.CLOSED) { // push notification or system kill
            val userId: String? = CacheUtil.getUser()?.userId
            SendBird.connect(userId,ConnectHandler { user,e ->
                if (e != null) {
                    return@ConnectHandler
                }
                handler(false)
            })
        }
    }

    fun removeConnectionManagementHandler(handlerId: String?) {
        SendBird.removeConnectionHandler(handlerId)
    }

}